package trunk;

import javafx.animation.Interpolator;
import javafx.animation.Timeline;
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.CustomNode;
import javafx.scene.paint.Color;
import javafx.scene.Node;
import javafx.scene.shape.Circle;
import java.lang.Math;

def HEIGHT = 600;
def WIDTH = 600;
def INITIAL_X_VELOCITY = 0.1;
def INITIAL_Y_VELOCITY = 0.45;

var ball: Ball;
var ball2: Ball;
var time: Number on replace OldValue {
    ball.move(time - OldValue, WIDTH, HEIGHT);
    ball2.move(time - OldValue, WIDTH, HEIGHT);
    if (ball.collide(ball2)) {
        timer.stop();
    }
};
var timer : Timeline = Timeline {
    keyFrames: [
        at (0ms) { time => 0 },
        at (1000000ms) { time => 1000000 tween Interpolator.LINEAR}
    ]
};

ball = Ball {
    x: 0
    y: HEIGHT-10
    velocity_x: INITIAL_X_VELOCITY
    velocity_y: -INITIAL_Y_VELOCITY
    radius: 10
    color: Color.WHITE,
    opacity: 1
}

ball2 = Ball {
    x: 400
    y: HEIGHT - 10
    velocity_x: -0.5
    velocity_y: -1
    radius: 10
    color: Color.WHITE
    opacity: 1
}

Stage {
    scene: Scene {
        fill: Color.GRAY
        content: [
            ball
            ball2
        ]
    };
    title: "Bouncy Bubbles"
    width: WIDTH +10
    height: HEIGHT + 29
}
timer.play();



class Ball extends CustomNode {
    def GRAVITY : Number = 0.0002;
    def WALL_HARDNESS = .90;
    public var x : Number;
    public var y : Number;
    public var radius : Number;
    public var color : Color = Color.WHITE;
    public var velocity_x : Number;
    public var velocity_y : Number;

    public function collide( other_ball : Ball ): Boolean {
        var dx : Number = other_ball.x - x;
        var dy : Number = other_ball.y - y;

        var distance : Number = Math.sqrt( dx * dx + dy * dy );
        var minDist : Number = other_ball.radius + radius;

        return ( distance < minDist )
    }

    public function move( delta_time: Number, width : Number, height : Number ): Void {
        velocity_y += GRAVITY*delta_time;
        velocity_x = velocity_x;
        y += velocity_y*delta_time;
        x += velocity_x*delta_time;
        if( x + radius > width ) {
            x = width - radius;
            velocity_x *= -WALL_HARDNESS;
        } else
        if( x - radius < 0 ) {
            x = radius;
            velocity_x *= -WALL_HARDNESS;
        }
        if( y + radius > height ) {
            y = height - radius;
            velocity_y *= -WALL_HARDNESS;
        } else
        if( y - radius < 0 ) {
            y = radius;
            velocity_y *= -WALL_HARDNESS;
        }
    }
    public override function create(): Node {
        return Circle {
            centerX: bind x, 
            centerY: bind y,
            radius: bind radius
            fill: bind color
        };
    }
}
